// ==UserScript==
// @name         防止未经授权的自动复制
// @version      28
// @description  在非选词复制时显示小红点提示用户以防止未经授权的自动复制，脚本菜单还加入了禁止写入剪贴板功能
// @author       DeepSeek
// @match        *://*/*
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_registerMenuCommand
// @grant        GM_setClipboard
// @run-at       document-start
// @namespace https://greasyfork.dpdns.org/users/452911
// @downloadURL https://update.greasyfork.dpdns.org/scripts/461625/%E9%98%B2%E6%AD%A2%E6%9C%AA%E7%BB%8F%E6%8E%88%E6%9D%83%E7%9A%84%E8%87%AA%E5%8A%A8%E5%A4%8D%E5%88%B6.user.js
// @updateURL https://update.greasyfork.dpdns.org/scripts/461625/%E9%98%B2%E6%AD%A2%E6%9C%AA%E7%BB%8F%E6%8E%88%E6%9D%83%E7%9A%84%E8%87%AA%E5%8A%A8%E5%A4%8D%E5%88%B6.meta.js
// ==/UserScript==

(function() {
    'use strict';

    // 获取当前域名
    const domain = window.location.hostname;

    // 获取当前域名对应的脚本启用状态
    let isEnabledClipboard = GM_getValue(domain + '_clipboard', false);
    let isEnabledAutoCopy = GM_getValue(domain + '_autocopy', true);

    // 注册菜单命令
    GM_registerMenuCommand((isEnabledClipboard ? '允许' : '禁止') + '写入剪贴板', () => {
        isEnabledClipboard = !isEnabledClipboard;
        GM_setValue(domain + '_clipboard', isEnabledClipboard);
        location.reload();
    });

    GM_registerMenuCommand((isEnabledAutoCopy ? '禁用' : '启用') + '复制监听', () => {
        isEnabledAutoCopy = !isEnabledAutoCopy;
        GM_setValue(domain + '_autocopy', isEnabledAutoCopy);
        location.reload();
    });

    // 如果脚本启用，禁用剪贴板相关操作
    if (isEnabledClipboard) {
        ['execCommand', 'writeText', 'write'].forEach(method => {
            const target = method === 'execCommand' ? document : navigator.clipboard;
            Object.defineProperty(target, method, {
                value: () => {},
                writable: false,
                configurable: false
            });
        });
    }

    if (!isEnabledAutoCopy) return;

    // 全局变量
    let redDot = null;
    let pendingCopyText = '';
    let timeoutId = null;
    let isUserSelection = false;
    let isInitialized = false;

    // 创建小红点元素
    function createRedDot() {
        if (redDot) return redDot;
        
        const dot = document.createElement('div');
        dot.innerHTML = '📋';
        dot.style.cssText = `
            position: fixed;
            right: 20px;
            top: 50%;
            transform: translateY(-50%);
            width: 40px;
            height: 40px;
            background: rgba(255, 0, 0, 0.7);
            border-radius: 50%;
            display: none;
            justify-content: center;
            align-items: center;
            cursor: pointer;
            z-index: 10000;
            font-size: 18px;
            color: white;
            box-shadow: 0 2px 10px rgba(0,0,0,0.3);
            transition: all 0.3s ease;
            pointer-events: auto;
        `;
        
        dot.addEventListener('mouseenter', function() {
            this.style.transform = 'translateY(-50%) scale(1.1)';
            this.style.background = 'rgba(255, 0, 0, 0.9)';
        });
        
        dot.addEventListener('mouseleave', function() {
            this.style.transform = 'translateY(-50%) scale(1)';
            this.style.background = 'rgba(255, 0, 0, 0.7)';
        });
        
        dot.addEventListener('click', handleRedDotClick);
        
        redDot = dot;
        return dot;
    }

    // 确保小红点存在
    function ensureRedDot() {
        if (!redDot && document.body) {
            createRedDot();
            document.body.appendChild(redDot);
        }
        return redDot;
    }

    function showRedDot() {
        const dot = ensureRedDot();
        if (dot) {
            dot.style.display = 'flex';
            // 5秒后自动隐藏
            timeoutId = setTimeout(() => {
                if (dot.style.display !== 'none') {
                    hideRedDot();
                }
            }, 5000);
        }
    }

    function hideRedDot() {
        if (redDot) {
            redDot.style.display = 'none';
        }
        pendingCopyText = '';
        if (timeoutId) {
            clearTimeout(timeoutId);
            timeoutId = null;
        }
    }

    // 点击小红点处理复制
    function handleRedDotClick() {
        if (!pendingCopyText) return;
        
        const promptText = `检测到复制请求，是否允许复制以下内容？\n\n"${pendingCopyText.substring(0, 100)}${pendingCopyText.length > 100 ? '...' : ''}"`;
        const allowCopy = confirm(promptText);
        
        if (allowCopy && typeof GM_setClipboard === "function") {
            GM_setClipboard(pendingCopyText);
        }
        hideRedDot();
    }

    // 监听用户选择文本的行为
    function setupSelectionTracking() {
        document.addEventListener('selectionchange', function() {
            const selection = window.getSelection();
            if (selection && selection.toString().length > 0) {
                isUserSelection = true;
            }
        });
    }

    // 拦截剪贴板API
    function setupClipboardInterception() {
        if (navigator.clipboard && navigator.clipboard.writeText) {
            const originalWriteText = navigator.clipboard.writeText;
            Object.defineProperty(navigator.clipboard, 'writeText', {
                value: function(text) {
                    // 如果是用户选择，直接允许复制
                    if (isUserSelection) {
                        isUserSelection = false;
                        return originalWriteText.call(navigator.clipboard, text);
                    }
                    
                    if (!text || text.trim().length === 0) return Promise.resolve();
                    
                    pendingCopyText = text;
                    showRedDot();
                    return Promise.resolve();
                },
                writable: true,
                configurable: true,
            });
        }
    }

    // 拦截execCommand
    function setupExecCommandInterception() {
        const originalExecCommand = document.execCommand;
        if (originalExecCommand) {
            Object.defineProperty(document, 'execCommand', {
                value: function(command) {
                    if (command === 'copy') {
                        const selection = window.getSelection();
                        if (selection && selection.toString().length > 0) {
                            // 如果是用户选择，直接执行复制
                            if (isUserSelection) {
                                isUserSelection = false;
                                return originalExecCommand.apply(document, arguments);
                            }
                            
                            pendingCopyText = selection.toString();
                            showRedDot();
                            return true;
                        }
                    }
                    return originalExecCommand.apply(document, arguments);
                },
                writable: true,
                configurable: true,
            });
        }
    }

    // 拦截copy事件
    function setupCopyEventInterception() {
        document.addEventListener('copy', function(e) {
            const selection = window.getSelection();
            if (selection && selection.toString().length > 0) {
                // 如果是用户选择，允许复制
                if (isUserSelection) {
                    isUserSelection = false;
                    return;
                }
                
                pendingCopyText = selection.toString();
                showRedDot();
                e.preventDefault();
                e.stopPropagation();
            }
        }, true);
    }

    // 设置触摸事件处理
    function setupTouchEvents() {
        let startX = null;
        let startY = null;

        document.addEventListener('touchstart', function(e) {
            startX = e.touches[0].clientX;
            startY = e.touches[0].clientY;
        });

        document.addEventListener('touchmove', function(e) {
            if (startX === null || startY === null) return;
            
            const currentX = e.touches[0].clientX;
            const currentY = e.touches[0].clientY;
            const diffX = Math.abs(currentX - startX);
            const diffY = Math.abs(currentY - startY);

            if ((diffX > 10 || diffY > 10) && redDot && redDot.style.display !== 'none') {
                hideRedDot();
            }
        });
    }

    // 初始化UI
    function initUI() {
        if (isInitialized) return;
        
        ensureRedDot();
        setupTouchEvents();
        isInitialized = true;
        
        console.log('防止自动复制脚本已初始化');
    }

    // 设置所有拦截
    function setupInterceptions() {
        setupSelectionTracking();
        setupClipboardInterception();
        setupExecCommandInterception();
        setupCopyEventInterception();
    }

    // 主初始化函数
    function initialize() {
        // 立即设置拦截
        setupInterceptions();
        
        // 根据文档状态初始化UI
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', initUI);
        } else {
            // 文档已经加载完成，直接初始化UI
            initUI();
        }
    }

    // 启动脚本
    initialize();

})();